#include <iostream>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <cstring>

// processA.cpp
int main() {
    // 定义键值和共享内存大小
    key_t key = ftok("shmfile", 65);
    int shm_id = shmget(key, 1024, 0666|IPC_CREAT);

    if (shm_id == -1) {
        perror("shmget failed");
        return 1;
    }

    // 将共享内存段附加到当前进程的地址空间
    char *str = (char*) shmat(shm_id, nullptr, 0);
    if (str == (char*)-1) {
        perror("shmat failed");
        return 1;
    }

    // 向共享内存写入数据
    const char* message = "I am process A";
    strncpy(str, message, 1024);

    std::cout << "Process A wrote: " << message << std::endl;

    // 分离共享内存段
    if (shmdt(str) == -1) {
        perror("shmdt failed");
        return 1;
    }

    return 0;
}
